<template>
	<view>
		<view class="cu-custom" :style="{'height':customBarHeight + 'px'}">
			<view class="cu-bar fixed justify-start padding-left-sm text-white"
				:style="{'height':customBarHeight + 'px','padding-top':statusBarHeight + 'px','background-color':themeConfig.primaryColor}">
				<picker @change="statusChange" :value="statusIndex" :range='statusList' range-key="label">
					<view class="text-df">
						{{formatStatusIndex(statusIndex).label}}
					</view>
				</picker>
				<view class="margin-right-sm margin-left-sm text-df">|</view>
				<picker mode="multiSelector" @change="productAndSeriesChange"
					@columnchange="productAndSeriesColumnchange" :value="productAndSeriesIndex"
					:range='productAndSeriesNameList'>
					<view class="text-df">
						{{productAndSeriesNameList[0][productAndSeriesIndex[0]]}} [
						{{productAndSeriesNameList[1][productAndSeriesIndex[1]]}} ]
					</view>
				</picker>
			</view>
		</view>
		<map :subkey="qqMapKey" id="myMap" ref="myMap" style="width:100%;"
			:style="{height:screenHeight-tabbarHeight-customBarHeight+'px'}" :scale="scale" :longitude="lng"
			:latitude="lat" :markers="markers" @markertap="markertap" @tap="mapTap" @regionchange="regionchange"></map>
		<view v-if="isShowDeviceList" class="ztnCustom-background-color" style="background: rgba(112, 200, 226,0.2);">
			<!-- <view class="cu-bar bg-white solid-bottom" :style="[{top:customBarHeight + 'px'}]"> -->
			<!-- <view class="flex align-center justify-start margin" style="white-space: nowrap">
					<text>{{$t('number')}} : {{totalDeviceNum}}</text>
				</view>
				<view class="flex align-center justify-end margin flex-sub" style="white-space: nowrap;">
					<picker @change="statusChange" :value="statusIndex" :range='statusList' range-key="label">
						<view class="padding-right-sm"
							:class="[statusIndex != 0 ? 'text-bold text-lg text-grey':'text-grey']">
							{{formatStatusIndex(statusIndex).label}}
						</view>
					</picker>
					<view>|</view>
					<picker @change="productChange" :value="productIndex" :range='productNameList'>
						<view class="padding-left-sm"
							:class="[productIndex != 0 ? 'text-bold text-lg text-grey':'text-grey']">
							{{productNameList[productIndex]}}
						</view>
					</picker>
				</view> -->

			<view class="bg-white"
				style="height:865rpx;position:fixed;bottom:0;width:100%;z-index:998;border-top-left-radius:20rpx;border-top-right-radius:20rpx;">
				<view class="margin-top-sm text-center" id="hideButton" @tap="hideDeviceList">
					<view class="ztnCustom-hideIcon cuIcon-unfold"></view>
				</view>
				<mescroll-uni ref="mescrollRef" @init="mescrollInit" height="800rpx" top="10" :down="downOption"
					@down="downCallback" :up="upOption" @up="pageGetDevice">
					<view v-for="(arrItem,arrIndex) in deviceList" :key="arrIndex">
						<view v-for="(item,index) in arrItem" :key="index">
							<device-list-item :device="item"></device-list-item>
						</view>
					</view>
				</mescroll-uni>
			</view>
			<!-- </view> -->
		</view>

		<view style="position:fixed;right:0;z-index: 1024" :style="[{top:customBarHeight + 'px'}]">
			<view class="text-center margin">
				<text class="cuIcon-list"
					style="border-top-left-radius:6px;border-bottom-left-radius:6px;padding: 15rpx 30rpx;font-size: 36rpx"
					:style="showMode == 'area' ? selectStyle : unselectStyle" @tap="tapMode('area')"></text>
				<text class="cuIcon-radiobox" form input label picker picker-view radio slider switch textarea
					style="padding: 15rpx 30rpx;font-size: 36rpx;"
					:style="showMode == 'point' ? selectStyle : unselectStyle" @tap="tapMode('point')"></text>
				<text class="cuIcon-tag"
					style="border-top-right-radius:6px;border-bottom-right-radius:6px;padding: 15rpx 30rpx;font-size: 36rpx;"
					:style="showMode == 'geo' ? selectStyle : unselectStyle" @tap="tapMode('geo')"></text>
			</view>
		</view>

		<view class="cu-modal" :class="showLoadingMuchTip?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content">{{$t('confirm')}}{{$t('load')}}</view>
					<view class="action" @tap="showLoadingMuchTip=false">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view class="padding-xl text-df">
					{{$t('load')}}{{deviceList.length}}{{$t('device')}}
				</view>
				<view class="cu-bar bg-white">
					<view class="action margin-0 flex-sub text-green solid-left" @tap="showLoadingMuchTip=false">
						{{$t('cancel')}}
					</view>
					<view class="action margin-0 flex-sub  solid-left" @tap="doSetPointMarkers">{{$t('confirm')}}</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		showLoading,
		hideLoading
	} from '@/util/toast.js'
	import {
		listDeviceStatus,
		listProductList,
		listProductSeries,
	} from '@/util/utils.js'
	import myConfig from '@/myConfig.js'
	import MescrollMixin from '@/components/mescroll-uni/mescroll-mixins.js';
	import DeviceListItem from '@/components/ztn-custom/DeviceListItem/index.vue'
	import * as iotDeviceApi from '@/api/iot/iotDeviceApi.js'
	import *
	as iotDeviceBelongApi from '@/api/iot/iotDeviceBelongApi.js'
	import * as iotProductApi from '@/api/iot/iotProductApi.js'
	import * as iotProductSeriesApi from '@/api/iot/iotProductSeriesApi.js'
	import * as iotProductUserApi from '@/api/iot/iotProductUserApi.js'
	import * as iotProductSeriesUserApi from '@/api/iot/iotProductSeriesUserApi.js'
	import * as storage from '@/util/storage.js'
	let mapContext = {}
	export default {
		name: 'DeviceMap',
		mixins: [MescrollMixin], // 使用mixin (在main.js注册全局组件)
		data() {
			return {
				downOption: {
					use: false,
					auto: false, //是否在初始化后,自动执行downCallback; 默认true
				},
				upOption: {
					empty: {
						use: true,
						fixed: true,
						top: '10%'
					}
				},
				customBarHeight: storage.getCustomBarHeight(),
				statusBarHeight: storage.getStatusBarHeight(),
				tabbarHeight: storage.getTabbarHeight(),
				screenHeight: storage.getScreenHeight(),
				showMode: '',
				selectStyle: '',
				unselectStyle: '',
				scale: 4.5,
				lng: null,
				lat: null,
				markers: [],
				markerId: Number,
				currentPage: 1,
				pageSize: 10,
				statusIndex: 0,
				statusList: [],
				productList: [],
				productSeriesList: [],
				productAndSeriesList: [
					[],
					[]
				],
				productAndSeriesNameList: [
					[],
					[]
				],
				productAndSeriesIndex: [0, 0],
				productId: null,
				seriesId: null,
				deviceList: [],
				isShowDeviceList: false,
				totalDeviceNum: 0,
				userId: storage.getUserId(),
				companyId: storage.getCompanyId(),
				deptId: storage.getDeptId(),
				websiteModel: storage.getWebsiteModel(),
				qqMapKey: myConfig.app.qqMapKey,
				showLoadingMuchTip: false
			}
		},
		emits: ['is-show-nav'],
		computed: {
			themeConfig() {
				return this.$store.state.themeConfig
			}
		},
		beforeMount() {
			const primaryColor = this.$store.state.themeConfig.primaryColor
			this.selectStyle = `background:${primaryColor};color:#fff;border:2rpx solid ${primaryColor}`
			this.unselectStyle = `background:#fff;color:${primaryColor};border:2rpx solid ${primaryColor}`
		},
		mounted() {
			this.init()
		},
		methods: {
			init() {
				const latLng = {
					lat: storage.getLat(),
					lng: storage.getLng(),
				}
				this.lat = latLng.lat
				this.lng = latLng.lng
				mapContext = uni.createMapContext('myMap', this)
				this.statusList = listDeviceStatus(this)
				this.statusIndex = storage.getStatusIndex()
				const productId = storage.getProductId()
				if (productId) {
					this.productId = parseInt(productId)
				}
				this.listProductAndSeries().then(res => {
					this.productAndSeriesList = [this.productList, this.productSeriesList]
					const index = this.productList.findIndex((item) => item.productId === this.productId)
					this.productAndSeriesIndex = [index, 0]
				})
				this.tapMode(storage.getMapModel())
			},
			listProductAndSeries: async function() {
				let api
				switch (this.websiteModel) {
					case 'system':
					case 'company':
					case 'dept':
						api = iotProductApi.listProduct({})
						break
					default:
						api = iotProductUserApi.listProduct({
							userId: this.userId
						})
				}

				await api.then((res) => {
					const {
						data
					} = res
					if (data) {
						this.productList = listProductList(this, data)
					}
				})


				if (this.productId) {
					await this.listSeries();
				} else {
					this.handleProductSeriesList([])
				}
			},
			listSeries() {
				return new Promise((resolve, reject) => {
					let api
					switch (this.websiteModel) {
						case 'system':
						case 'company':
						case 'dept':
							api = iotProductSeriesApi.listSeries({
								productId: this.productId
							})
							break
						default:
							api = iotProductSeriesUserApi.listSeries({
								userId: this.userId,
								productId: this.productId
							})
					}
					api.then((res) => {
						const {
							data
						} = res
						if (data) {
							this.handleProductSeriesList(data)
							resolve()
						}
					})
				})
			},
			makeProductAndSeriesNameList() {
				const productNameList = []
				this.productList.forEach(item => {
					productNameList.push(item.name)
				})
				const productSeriesNameList = []
				this.productSeriesList.forEach(item => {
					productSeriesNameList.push(item.name)
				})
				this.productAndSeriesNameList = [productNameList, productSeriesNameList]
			},
			handleProductSeriesList(data) {
				this.productSeriesList = listProductSeries(this, data)
				this.makeProductAndSeriesNameList()
			},
			productAndSeriesColumnchange(e) {
				// console.log('修改的列为：' + e.detail.column + '，值为：' + e.detail.value)
				const column = e.detail.column
				const value = e.detail.value
				switch (column) {
					case 0: //拖动第1列
						if (value != 0) {
							this.productId = this.productList[value].productId
							this.listSeries().then((res) => {
								this.productAndSeriesIndex = [value, 0]
							})
						} else {
							this.productAndSeriesIndex = [0, 0]
						}
						break;
					case 1:
						this.productAndSeriesIndex = [this.productAndSeriesIndex[0], value]
						break
					default:
						break;
				}
				this.$forceUpdate()
			},
			productAndSeriesChange(e) {
				const index = e.detail.value
				this.productAndSeriesIndex = index
				this.productId = this.productList[index[0]].productId
				storage.setProductId(this.productId)
				this.seriesId = this.productSeriesList[index[1]].seriesId
				this.tapMode(storage.getMapModel())
			},
			statusChange(e) {
				this.statusIndex = e.detail.value
				storage.setStatusIndex(this.statusIndex)
				this.tapMode(storage.getMapModel())
			},
			resetMapParam() {
				this.markers = []
				this.markerId = null
			},
			formatStatusIndex(index) {
				return this.statusList[index]
			},
			tapMode(showMode) {
				this.resetMapParam()
				this.currentPage = 1
				this.deviceList = []
				this.showMode = showMode
				storage.setMapModel(showMode)
				switch (showMode) {
					case 'area':
						this.scale = 4.5
						this.listProvinceNum()
						break
					case 'point':
						this.scale = 8
						this.listDevice()
						break
					case 'geo':
						this.scale = 8
						this.listDeviceGEO()
						break
				}
			},
			listProvinceNum() {
				let api
				switch (this.websiteModel) {
					case 'system':
						api = iotDeviceApi.listProvinceNumAll({
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							seriesId: this.seriesId,
						})
						break
					case 'company':
						api = iotDeviceApi.listProvinceNumByCompany({
							companyId: this.companyId,
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							seriesId: this.seriesId,
						})
						break
					case 'dept':
						api = iotDeviceApi.listProvinceNumByDept({
							deptId: this.deptId,
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							seriesId: this.seriesId,
						})
						break
					default:
						api = iotDeviceBelongApi.listProvinceNum({
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							seriesId: this.seriesId,
						})
				}


				api.then((res) => {
					const {
						data
					} = res
					if (data) {
						this.resetMapParam()
						this.setAreaMarkers(data)
					}
				})
			},
			listCityNum() {
				let api
				switch (this.websiteModel) {
					case 'system':
						api = iotDeviceApi.listCityNumAll({
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							seriesId: this.seriesId,
						})
						break
					case 'company':
						api = iotDeviceApi.listCityNumByCompany({
							companyId: this.companyId,
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							seriesId: this.seriesId,
						})
						break
					case 'dept':
						api = iotDeviceApi.listCityNumByDept({
							deptId: this.deptId,
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							seriesId: this.seriesId,
						})
						break
					default:
						api = iotDeviceBelongApi.listCityNum({
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							seriesId: this.seriesId,
						})
				}
				api.then((res) => {
					const {
						data
					} = res
					if (data) {
						this.resetMapParam()
						this.setAreaMarkers(data)
					}
				})
			},
			setAreaMarkers(data) {
				this.markers = []
				const markers = []
				for (let i = 0, j = data.length; i < j; i++) {
					const item = data[i]
					if(!item.lat){
						continue
					}
					const latLng = {
						lat: item.lat,
						lng: item.lng
					}
					// if (i === 0) {
					// 	this.lat = latLng.lat
					// 	this.lng = latLng.lng
					// }
					let iconPath
					if (item.num >= 99) {
						iconPath =
							`${myConfig.app.baseUrl}/file/download/static/iot/uni/map/numsImage/${this.$store.state.themeConfig.theme}/local_99.png`
					} else {
						iconPath =
							`${myConfig.app.baseUrl}/file/download/static/iot/uni/map/numsImage/${this.$store.state.themeConfig.theme}/local_${item.num}.png`
					}
					const marker = {
						id: i,
						width: 35,
						height: 35,
						latitude: latLng.lat,
						longitude: latLng.lng,
						iconPath: iconPath,
						provinceId: item.provinceId,
						cityId: item.cityId,
					}
					markers.push(marker)
				}
				this.markers = markers
			},
			setPointMarkers(data) {
				this.deviceList = data
				if (data.length > 1000) {
					this.showLoadingMuchTip = true
				} else {
					this.doSetPointMarkers()
				}
			},
			doSetPointMarkers() {
				this.showLoadingMuchTip = false
				showLoading(this.$t('loading'), true)
				this.markers = []
				const markers = []
				for (let i = 0, j = this.deviceList.length; i < j; i++) {
					const item = this.deviceList[i]
					const latLng = {
						lat: item.lat,
						lng: item.lng
					}
					if (i === 0) {
						this.lat = latLng.lat
						this.lng = latLng.lng
					}
					const marker = {
						id: i,
						width: 35,
						height: 35,
						latitude: latLng.lat,
						longitude: latLng.lng,
						iconPath: item.iconUrl,
						deviceName: item.deviceName,
						deviceCore: item.deviceCore,
						// joinCluster: true,
						// label:{
						// 	width: 80,
						// 	height: 20,
						// 	borderWidth: 1,
						// 	borderRadius: 10,
						// 	bgColor: '#ffffff',
						// 	content: item.deviceName
						// }
					}
					markers.push(marker)
				}
				// mapContext.addMarkers({
				// 	markers,
				// 	clear: false,
				// 	complete(res) {
				// 		console.log('addMarkers', res)
				// 	}
				// })
				this.markers = markers
				const that = this
				setTimeout(() => {
					hideLoading()
				}, 0)
			},
			markertap(e) {
				this.markerId = e.detail.markerId
				switch (this.showMode) {
					case 'area':
						this.markertapAreaMode()
						break
					case 'geo':
					case 'point':
						this.markertapPointOrGeoMode()
						break
				}
			},
			mapTap(e) {
				this.lat = e.detail.latitude
				this.lng = e.detail.longitude
				if (this.showMode === 'geo') {
					this.listDeviceGEO()
				}
			},
			markertapAreaMode() {
				const {
					provinceId,
					cityId
				} = this.markers[this.markerId]
				this.provinceId = provinceId
				this.cityId = cityId
				this.isShowDeviceList = true
				this.$emit('is-show-nav', false);
				this.currentPage = 1
			},
			markertapPointOrGeoMode() {
				const {
					deviceCore,
				} = this.markers[this.markerId]
				const component = storage.getDeviceNavigationComponent()
				uni.navigateTo({
					url: `/pages/deviceNavigation/deviceNavigation?deviceCore=${deviceCore}&component=${component}`
				})
			},

			pageGetDevice() {
				let api
				switch (this.websiteModel) {
					case 'system':
						api = iotDeviceApi.pageGetAllDevice({
							provinceId: this.provinceId,
							cityId: this.cityId,
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							seriesId: this.seriesId,
							currentPage: this.currentPage,
							pageSize: this.pageSize
						})
						break
					case 'company':
						api = iotDeviceApi.pageGetCompanyDevice({
							companyId: this.companyId,
							provinceId: this.provinceId,
							cityId: this.cityId,
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							seriesId: this.seriesId,
							currentPage: this.currentPage,
							pageSize: this.pageSize
						})
						break
					case 'dept':
						api = iotDeviceApi.pageGetDeptDevice({
							deptId: this.deptId,
							provinceId: this.provinceId,
							cityId: this.cityId,
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							seriesId: this.seriesId,
							currentPage: this.currentPage,
							pageSize: this.pageSize
						})
						break
					default:
						api = iotDeviceBelongApi.pageGetDevice({
							provinceId: this.provinceId,
							cityId: this.cityId,
							productId: this.productId,
							seriesId: this.seriesId,
							status: this.statusList[this.statusIndex].value,
							currentPage: this.currentPage,
							pageSize: this.pageSize
						})
				}

				api.then(res => {
					const {
						data
					} = res
					if (data) {
						this.totalDeviceNum = data.total
						this.mescroll.endByPage(data.data.length, data.total)
						this.$set(this.deviceList, data.currentPage - 1, data.data)
						this.currentPage = data.currentPage + 1
					}
				})
			},
			listDevice() {
				showLoading(this.$t('loading'), true)
				let api
				switch (this.websiteModel) {
					case 'system':
						api = iotDeviceApi.listAllDevice({
							productId: this.productId,
							seriesId: this.seriesId,
							status: this.statusList[this.statusIndex].value,
						})
						break
					case 'company':
						api = iotDeviceApi.listCompanyDevice({
							companyId: this.companyId,
							productId: this.productId,
							seriesId: this.seriesId,
							status: this.statusList[this.statusIndex].value,
						})
						break
					case 'dept':
						api = iotDeviceApi.listDeptDevice({
							deptId: this.deptId,
							productId: this.productId,
							seriesId: this.seriesId,
							status: this.statusList[this.statusIndex].value,
						})
						break
					default:
						api = iotDeviceBelongApi.listDevice({
							productId: this.productId,
							seriesId: this.seriesId,
							status: this.statusList[this.statusIndex].value,
						})
				}

				api.then((res) => {
					const {
						data
					} = res
					if (data) {
						this.resetMapParam()
						this.setPointMarkers(data)
						setTimeout(() => {
							hideLoading()
						}, 0)
					}
				})
			},
			listDeviceGEO() {
				showLoading(this.$t('loading'), true)
				const latLng = {
					lat: this.lat,
					lng: this.lng
				}
				let api
				switch (this.websiteModel) {
					case 'system':
						api = iotDeviceApi.listAllDeviceGEO({
							productId: this.productId,
							seriesId: this.seriesId,
							status: this.statusList[this.statusIndex].value,
							lat: latLng.lat,
							lng: latLng.lng,
							geoHash: 3
						})
						break
					case 'company':
						api = iotDeviceApi.listAllDeviceGEO({
							companyId: this.companyId,
							productId: this.productId,
							seriesId: this.seriesId,
							status: this.statusList[this.statusIndex].value,
							lat: latLng.lat,
							lng: latLng.lng,
							geoHash: 3
						})
						break
					case 'dept':
						api = iotDeviceApi.listAllDeviceGEO({
							deptId: this.deptId,
							productId: this.productId,
							seriesId: this.seriesId,
							status: this.statusList[this.statusIndex].value,
							lat: latLng.lat,
							lng: latLng.lng,
							geoHash: 3
						})
						break
					default:
						api = iotDeviceBelongApi.listDeviceGEO({
							productId: this.productId,
							seriesId: this.seriesId,
							status: this.statusList[this.statusIndex].value,
							lat: latLng.lat,
							lng: latLng.lng,
							geoHash: 3
						})

				}

				api.then((res) => {
					const {
						data
					} = res
					if (data) {
						this.markers = []
						this.setPointMarkers(data)
						setTimeout(() => {
							hideLoading()
						}, 0)

					}
				})
			},
			getScale() {
				return new Promise((resolve) => {
					mapContext.getScale({
						success: (e) => {
							resolve(e)
						}
					})
				})
			},
			regionchange() {
				if (this.showMode === 'area') {
					mapContext.getScale({
						success: (e) => {
							if (e.scale < 6) {
								this.listProvinceNum()
							} else if (e.scale >= 6) {
								this.listCityNum()
							}
						}
					})
				}
			},
			hideDeviceList() {
				this.isShowDeviceList = false
				this.$emit('is-show-nav', true);
				this.productIndex = 0
				this.currentPage = 1
				this.deviceList = []
			}
		},
		components: {
			DeviceListItem
		}
	}
</script>

<style scoped>
	.ztnCustom-background-color {
		position: fixed;
		width: 100vw;
		height: 100vh;
		top: 0;
		z-index: 998;
		background: rgba(0, 0, 0, 0.6);

	}

	.ztnCustom-hideIcon {
		height: 45rpx;
		text-align: center;
	}

</style>
